<template>
	<div class="HouseApply">
		<div class="HouseApply-onebox">
			<div class="ho-top">
				<div class="hot-left">
					<img class="hotl-img" :src="houseinfo.houseImg" />
				</div>
				<div class="hot-right">
					<div class="hotr-title">{{houseinfo.title}}</div>
					<p v-if="houseinfo.houseRent==1">{{houseRent}} </p>
					<p v-if="houseinfo.roomRent==1">{{roomRent}}</p>
					<p v-if="houseinfo.bedRental==1">{{bedRental}} </p>
					<p>{{houseinfo.room}}室/宜居{{houseinfo.personNumber}}人</p>
				</div>
			</div>

			<div class="ho-tiemtitle" style="display: flex;justify-content: center;">
				<div id="firstSelect">
					<div class="hot-rz">
						<div class="hotr-label">入住：</div>
						<div class="hotr-label labeldate" id="startDate">{{startDate}}</div>
					</div>
					<div class="hot-ds">
						共<span class="NumDate">{{NumDate}}</span>晚
					</div>
					<div class="hot-rz">
						<div class="hotr-label">离开：</div>
						<div class="hotr-label labeldate" id="endDate">{{endDate}}</div>

					</div>
				</div>
				<div class="mask_calendar">
					<div class="calendar" ref="setData"></div>
					<!-- 提示 -->
					<div class="calendar_tishi">请选择离开日期...</div>
				</div>
				<span class="more" style="position: absolute;right: .24rem;"></span>
			</div>
		</div>

		<div class="HouseApply-houseinfo">
			<div class="hh-item">
				<div class="hhi-left">
					<span>入</span> <span>住  </span><span>人</span>
				</div>
				<router-link to="/ChoiceNum">
					<div class="hhi-right">
						<span class="hhir-g" v-if="userCheckInList==0||userCheckInList.length==0">请选择入住人</span>
						<span class="hhir-g" v-else>已选择{{userCheckInList.length}}人</span>
						<span class="more"></span>
					</div>
				</router-link>
			</div>
			<div class="hh-item" v-if="houseinfo.bedRental==1">
				<div class="hhi-left">
					<span>床</span> <span>位</span>
				</div>
				<div class="hhi-right">

					<router-link to="/bedsList">
						<div style="display: flex;">
							<span class="hhir-g" v-if="bedsId==null">请选择床位</span>
							<span class="hhir-g" v-if="bedsId!=null">{{bedsNo}}床</span>
							<span class="more"></span>
						</div>
					</router-link>
				</div>
			</div>
			<div class="hh-item">
				<div class="hhi-left">
					<span>优</span>　　<span>惠</span>
				</div>
				<div class="hhi-right">

					<span class="hhir-g" v-if="CouponList==0">暂无优惠券可用</span>
					<router-link to="/ChoiceCoupon">
						<div style="display: flex;">
							<span v-if="CouponList!=0&&allPriceCoupon==0">{{CouponList}}张可用</span>
							<span v-if="CouponList!=0&&allPriceCoupon!=0">已优惠{{allPriceCoupon}}元</span>
							<span class="more"></span>
						</div>
					</router-link>
				</div>
			</div>
		</div>

		<div class="HouseApply-houseinfo">
			<div class="hh-item">
				<div class="hhi-left">
					<span>预</span>　　<span>订</span><span>人</span>
				</div>
				<div class="hhi-right">

					<span>{{baseInfodata.userName}}</span>
					<span class="more"></span>
				</div>
			</div>
			<div class="hh-item">
				<div class="hhi-left">
					<span>联</span>　　<span>系</span><span>电</span>　　<span>话</span>
				</div>
				<div class="hhi-right">

					<span>{{baseInfodata.phone}}</span>
					<span class="more"></span>
				</div>
			</div>
			<div class="hh-item" v-if="refunM!=0" @click="ShortRulesGO">
				<div class="hhi-leftb">
					<div class="hhil-o">{{refunM}}月{{refunD}}日{{houseinfo.check_in_time}}前取消订单，全额退款</div>
					<div class="hhil-t">{{refunM}}月{{refunD}}日{{houseinfo.check_in_time}}后取消订单，扣除后{{houseinfo.sum_refunddays}}天的租金作为违约金</div>
				</div>
				<div class="hhi-right">
					<span class="more"></span>
				</div>
			</div>
		</div>

		<div class="HouseApply-flexbtn">
			<div class="hf-left">
				<div class="hfl-left">
					<p>订单总额：￥
						<span>{{price}}</span>
					</p>
					<span v-if="houseinfo.cashPledge==0">含押金0.0元</span>
					<span v-else>含押金{{houseinfo.cashPledge}}元</span>
				</div>
				<div class="hfl-right"><img class="hflr-img" src="../assets/img/images/haorder_03.png" /></div>
			</div>
			<div class="hf-right" @click="submintGetordernew">提交订单</div>
		</div>

	</div>
</template>

<script>
	import { mapGetters, mapActions } from 'vuex'
	import api from '../fetch/api'
	import housedata3 from "../../static/housedata3.js";
	export default {
		name: "HouseApply",
		data() {
			return {
				houseId: this.$route.query.houseId,
				houseinfo: [],
				price: "--",
				discountPrices: 0,
				couponPrices: 0,
				NumDate: 0,
				startDate: '——',
				endDate: "——",
				CouponList: 0,
				refunM: 0,
				refunD: 0,
				isFirstEnter: false, // 是否第一次进入，默认false
			}
		},
		beforeRouteEnter(to, from, next) {
			// 路由导航钩子，此时还不能获取组件实例 `this`，所以无法在data中定义变量（利用vm除外）
			// 参考 https://router.vuejs.org/zh-cn/advanced/navigation-guards.html
			// 所以，利用路由元信息中的meta字段设置变量，方便在各个位置获取。这就是为什么在meta中定义isBack
			// 参考 https://router.vuejs.org/zh-cn/advanced/meta.html
			if(from.name == 'ShortRules' || from.name == "ChoiceCoupon" || from.name == "ChoiceNum" || from.name == "bedsList") {
				to.meta.isBack = true;
				//判断是从哪个路由过来的，
				//如果是page2过来的，表明当前页面不需要刷新获取新数据，直接用之前缓存的数据即可
			}
			next();
		},
		activated() {
			var that = this;
			if(!that.$route.meta.isBack || that.isFirstEnter) {
				that.houseId = this.$route.query.houseId;
				that.houseinfo = JSON.parse(this.shorthouseinfo);
				that.setbedsList(JSON.parse(that.houseinfo.bedsList))
				that.price = "--";
				that.discountPrices = 0;
				that.couponPrices = 0;
				that.NumDate = 0;
				that.startDate = '——';
				that.endDate = "——";
				that.CouponList = 0;
				that.refunM = 0;
				that.refunD = 0;
				that.isFirstEnter = false; // 是否第一次进入，默认false
				$(".daysprice").remove();
				that.datetime();
				that.setBaseInfo()
				that.setAllPriceCoupon(0)
				that.setcouponId("");
				that.setuserCheckInList(0)
				that.setAllprice(0);
				$(".NumDate").text(0)

				that.setbedsId(null);
			} else {}
			that.JSallPrice();
			// 恢复成默认的false，避免isBack一直是true，导致下次无法获取数据
			that.$route.meta.isBack = false
			// 恢复成默认的false，避免isBack一直是true，导致每次都获取新数据
			that.isFirstEnter = false;
		},
		created() {
			var that = this;
			that.isFirstEnter = true;
			// 只有第一次进入或者刷新页面后才会执行此钩子函数
			// 使用keep-alive后（2+次）进入不会再执行此钩子函数
		},
		//		mounted() {
		//			this.datetime()
		//			this.setBaseInfo()
		//		},
		computed: {
			...mapGetters([
				'source',
				'ShortPricesdata',
				'ShortPricesTimedata',
				'houseRent',
				'roomRent',
				'bedRental',
				'baseInfodata',
				'allPrice',
				'allPriceCoupon',
				'userCheckInList',
				'couponId',
				'bedsId',
				'bedsNo',
				'shorthouseinfo'
			])
		},
		methods: {
			...mapActions({
				setBaseInfo: 'setBaseInfo',
				setAllprice: 'setAllprice',
				setAllPriceCoupon: "setAllPriceCoupon",
				setcouponId: 'setcouponId',
				setuserCheckInList: "setuserCheckInList",
				setbedsList: "setbedsList",
				setbedsId: "setbedsId"
			}),
			//			提交订单
			submintGetordernew() {
				if(this.startDate == "——") {
					alert("请选择入住时间")
					return;
				}
				if(this.userCheckInList == 0) {
					alert("请选择入住人")
					return;
				}
				if(this.houseinfo.bedRental == 1 && this.bedsId == null) {
					alert("请选择床位")
					return;
				}
				var ajaxSign = {
					"source": this.source, // string 是
					"token": this.baseInfodata.token, //string 是
					"userId": this.baseInfodata.id.toString(), //string 是
					"houseId": this.houseId.toString(), //string 是 房源id
					"contactPhone": this.baseInfodata.phone, //string 是 联系人电话
					"contactName": this.baseInfodata.userName, //string 是 联系人姓名
					"originalPrices": this.allPrice.toString(), //string 是 原始价格(见详情)
					"number": this.NumDate.toString(), //string 是 数量(天数)
					"prices": this.houseinfo.prices.toString(), //string 是 单价
					"userCheckInList": this.userCheckInList.join(","), //string 是 入住人id串
					"houseStartTime": this.startDate.toString(), //string 是 入住时间 2018 - 03 - 31
					"houseEndTime": this.endDate.toString(), //string 是 退房时间 2018 - 04 - 23
					"payPrices": this.price.toString(), //string 是 支付价格(见详细说明)
					"describe": "", //string 是 备注(选填)
					"bedsId": this.bedsId, //string 是 床铺id(床位租时传入)
					"discountPrices": this.discountPrices.toString(), //string 是 折扣价格(满足折扣时传入)
					"couponId": this.couponId.toString(), //string 是 优惠券id(有优惠券时传入)
					"couponPrices": this.couponPrices.toString() //string 是 优惠券价格(有优惠券时传入)
				};
				let ajaxData = api.getAES(ajaxSign);
				//				获取房源特定价格
				api.Getordernew(ajaxData)
					.then(res => {
						if(res.sta == 200) {
							this.$router.replace({
								path: "/ToderInfo",
								query: {
									orderId: res.result.orderId,
									userType: "1",
								}
							})
						}
					})
			},
			JSallPrice() {
				//				初始总价格
				let jallPrice = this.allPrice;
				if(jallPrice > 0) {
					//				如果有折扣
					if(this.houseinfo.fullCuts != undefined) {
						for(var i = 0; i < this.houseinfo.fullCuts.length; i++) {
							if(parseInt(this.NumDate) >= parseInt(this.houseinfo.fullCuts[i].days)) {
								//							折扣后的价格
								this.discountPrices = (jallPrice * (1 - parseFloat(this.houseinfo.fullCuts[i].discount) / 10)).toFixed(2);
								jallPrice = parseFloat(this.houseinfo.fullCuts[i].discount) / 10 * jallPrice;
							}
						}
					}
					jallPrice = jallPrice + this.houseinfo.cashPledge + this.houseinfo.cleanFee - this.allPriceCoupon;
					this.couponPrices = this.allPrice - this.discountPrices + this.houseinfo.cleanFee
					if(jallPrice <= 0) {
						jallPrice = 0
					}
					this.price = jallPrice.toFixed(2)
				}
				//				this.setAllprice(jallPrice)
			},
			ShortRulesGO() {
				var that = this;
				that.$router.push({
					path: "/ShortRules",
					query: {
						houseId: that.houseId
					}
				})
			},
			setpricetime() {

				var that = this,
					ShortPrices = '',
					ShortPricesTime = '';
				//				转为时间戳
				var date = new Date();
				date.setDate(date.getDate() - 1); //获取AddDayCount天后的日期 
				var time1 = date.getTime() / 1000;
				var today = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
				var preDate = new Date(date.getTime() - 24 * 60 * 60 * 1000); //前一天
				var ajaxSign = {
					"source": that.source,
					"houseId": that.houseId.toString(),
					"times": time1.toString()
				};

				let ajaxData = api.getAES(ajaxSign);
				//				获取房源特定价格
				api.GetShortPrices(ajaxData)
					.then(res => {
						ShortPrices = res.result;

						for(var i = 0; i < $(".days").length; i++) {
							//				该天的上一个兄弟节点。
							let daysprev = $(".days").eq(i).parents("table").prev().text(),
								//				该天对应的年
								prevyear = parseInt(daysprev.split("年")[0]),
								//				该天对应的月
								pravmonth = parseInt(daysprev.split("年")[1].split("月")[0]),
								//						该天
								day = $(".days").eq(i).text();

							let dayspricetime = new Date(prevyear + "-" + pravmonth + "-" + day);
							if(preDate < dayspricetime) {
								$(".days").eq(i).parent("td").append("<p class='daysprice'>￥" + that.houseinfo.prices + "</p>")
								$(".daysprice").eq(0).parent("td").css("color", "#282828")
							}

							//						房源已购买时间
							for(var j = 0; j < ShortPrices.length; j++) {
								var date1 = new Date(ShortPrices[j].times * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
								//									房源已购买时间-年
								var Y = parseInt(date1.getFullYear());
								//									房源已购买时间-月
								var M = parseInt(date1.getMonth() + 1 < 10 ? '0' + (date1.getMonth() + 1) : date1.getMonth() + 1);
								//									房源已购买时间-日
								var D = parseInt(date1.getDate());

								if(prevyear == Y) {
									if(pravmonth == M) {
										if(day == D) {
											var teshudays = new Date(Y + "-" + M + "-" + D);
											//												当前时间小于房源已购买时间就显示已购买时间的房源状态

											if(preDate < teshudays) {
												if(ShortPrices[j].status == 1) {
													//														$(".days").eq(i).parent("td").append("<p>已租</p>")
													$(".days").eq(i).parent("td").find(".daysprice").html("已租")
												}
												if(ShortPrices[j].status == 0) {
													//														$(".days").eq(i).parent("td").append("<p>"+"￥"+ShortPrices[j].prices+"</p>")
													$(".days").eq(i).parent("td").find(".daysprice").html("￥" + ShortPrices[j].prices)
												}
											}
										}
									}
								}

							}
						}

					})
				//获取房源已购买时间
				api.GetShortPricesTime(ajaxData)
					.then(res => {
						if(res.sta == 200) {
							ShortPricesTime = res.result

							for(var i = 0; i < $(".days").length; i++) {
								//				该天的上一个兄弟节点。
								let daysprev = $(".days").eq(i).parents("table").prev().text(),
									//				该天对应的年
									prevyear = parseInt(daysprev.split("年")[0]),
									//				该天对应的月
									pravmonth = parseInt(daysprev.split("年")[1].split("月")[0]),
									//						该天
									day = $(".days").eq(i).text();

								//						房源已购买时间
								for(var j = 0; j < ShortPricesTime.length; j++) {
									var date1 = new Date(ShortPricesTime[j].times * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
									//									房源已购买时间-年
									var Y = parseInt(date1.getFullYear());
									//									房源已购买时间-月
									var M = parseInt(date1.getMonth() + 1 < 10 ? '0' + (date1.getMonth() + 1) : date1.getMonth() + 1);
									//									房源已购买时间-日
									var D = parseInt(date1.getDate());

									if(prevyear == Y) {
										if(pravmonth == M) {
											if(day == D) {
												var teshudays = new Date(Y + "-" + M + "-" + D);
												//												当前时间小于房源已购买时间就显示已购买时间的房源状态
												if(preDate < teshudays) {
													if(ShortPricesTime[j].status == 1) {
														$(".days").eq(i).parent("td").append("<p>已租</p>")
													}
												}
											}
										}
									}

								}
							}

						}
					})

			},
			gettimego(times) {
				var date1 = new Date(times * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
				var Y = date1.getFullYear();
				var M = (date1.getMonth() + 1 < 10 ? '0' + (date1.getMonth() + 1) : date1.getMonth() + 1);
				var D = date1.getDate();
				return date1
			},
			datetime() {
				var that = this;
				$('#firstSelect').on('click', function(e) {
					e.stopPropagation();
					e.preventDefault();
					$('.mask_calendar').show();
				});
				$('.mask_calendar').on('click', function(e) {
					e.stopPropagation();
					e.preventDefault();
					if(e.target.className == "mask_calendar") {
						$('.calendar').slideUp(200);
						$('.mask_calendar').fadeOut(200);
					}
				})
				$('#firstSelect').calendarSwitch({
					selectors: {
						sections: ".calendar"
					},
					index: 7, //展示的月份个数
					animateFunction: "slideToggle", //动画效果
					controlDay: true, //知否控制在daysnumber天之内，这个数值的设置前提是总显示天数大于90天
					daysnumber: "210", //控制天数
					comeColor: "#e25051", //入住颜色
					outColor: "#e25051", //离店颜色
					comeoutColor: "#ffb0b1", //入住和离店之间的颜色
					callback: function() { //回调函数
						$('.mask_calendar').fadeOut(200);
						var startDate = $('#startDate').val(); //入住的天数
						that.startDate = startDate;
						var endDate = $('#endDate').val(); //离店的天数
						that.endDate = endDate;
						var NumDate = $('.NumDate').text(); //共多少晚
						that.NumDate = NumDate;
						//						that.isdatetitle = false

						//下面做ajax请求
					},
					comfireBtn: '.comfire' //确定按钮的class或者id

				});

				$(".comfire").on("click", function() {
					let rz = $(".rz");
					let backred = $(".backred");
					let comprice = 0;
					for(var i = 0; i < backred.length; i++) {
						comprice += parseFloat(backred.eq(i).find(".daysprice").text().split("￥")[1]);
					}
					comprice += parseFloat(rz.eq(0).siblings(".daysprice").text().split("￥")[1]);
					that.setAllprice(comprice);
					that.JSallPrice();
					let ajaxSign = {
						"source": that.source,
						"token": that.baseInfodata.token,
						"payPrices": comprice.toString(), //	string	否	在个人信息里面 不传payPrices		
						"type": '1' //	string	否	1可以 2不可以 3过期
					}

					let ajaxData = api.getAES(ajaxSign);
					api.GetCouponList(ajaxData)
						.then(res => {
							that.CouponList = res.result.length;
							if(res.sta == 203) {
								that.$router.push({
									path: "/login"
								})
							}
							if(res.sta == 200) {
								that.CouponList = res.result.length;
							}
						});
					var refunddaysdata = new Date(that.startDate);
					var timesday = refunddaysdata.setDate(refunddaysdata.getDate() - that.houseinfo.sum_refunddays); //获取AddDayCount天后的日期 
					var date2 = new Date(timesday);
					that.refunM = date2.getMonth() + 1 < 10 ? '0' + (date2.getMonth() + 1) : date2.getMonth() + 1;
					that.refunD = date2.getDate() < 10 ? '0' + date2.getDate() : date2.getDate();
				})
				var b = new Date();
				var ye = b.getFullYear();
				var mo = b.getMonth() + 1;
				mo = mo < 10 ? "0" + mo : mo;
				var da = b.getDate();
				da = da < 10 ? "0" + da : da;
				$('#startDate').val(ye + '-' + mo + '-' + da);
				b = new Date(b.getTime() + 24 * 3600 * 1000);
				var ye = b.getFullYear();
				var mo = b.getMonth() + 1;
				mo = mo < 10 ? "0" + mo : mo;
				var da = b.getDate();
				da = da < 10 ? "0" + da : da;
				$('#endDate').val(ye + '-' + mo + '-' + da);
				this.setpricetime()
			},
		}
	}
</script>

<style>
	@import url("../assets/css/caldate.css");
	@import url("../assets/css/cldate1.css");
	.HouseApply .dateTable td>p {
		font-size: .15rem;
		color: #282828;
	}
	
	.HouseApply .dateTable .rz {
		color: #fff !important;
	}
	
	.HouseApply .dateTable .rz>p {
		color: #fff !important;
	}
	
	.HouseApply {
		width: 100%;
		font-size: .31rem;
		line-height: .31rem;
	}
	
	.HouseApply .HouseApply-onebox {
		width: 100%;
		background: #fff;
	}
	
	.HouseApply .ho-top {
		display: flex;
		padding: .49rem .24rem;
		border-bottom: 1px solid #EEECEC;
		box-sizing: border-box;
	}
	
	.HouseApply .hot-left {
		width: 2.15rem;
		height: 1.42rem;
		overflow: hidden;
	}
	
	.HouseApply .hotl-img {
		display: block;
		max-width: 100%;
		min-height: 100%;
	}
	
	.HouseApply .hotr-title {
		font-size: .31rem;
		line-height: .31rem;
		width: 4.34rem;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.HouseApply .hot-right {
		margin-left: .42rem;
	}
	
	.HouseApply .hot-right>p {
		font-size: .25rem;
		line-height: .25rem;
		color: #747474;
		margin-top: .31rem;
	}
	/*入住离开*/
	
	.HouseApply .ho-tiemtitle {
		display: flex;
		justify-content: space-between;
		padding: .47rem .24rem;
		box-sizing: border-box;
	}
	
	.HouseApply .hot-rz {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	
	.HouseApply .hot-ds {
		width: 1.29rem;
		font-size: .27rem;
		text-align: center;
		position: relative;
	}
	
	.HouseApply .hot-ds::after {
		content: "";
		display: block;
		width: 100%;
		height: 1px;
		background: #282828;
		position: absolute;
		bottom: -.05rem;
	}
	
	.HouseApply .hot-ds>span {
		color: #e34648;
	}
	
	.HouseApply .more {
		display: block;
		width: .23rem;
		height: .23rem;
		border: 1px solid #bcbcbc;
		border-bottom: none;
		border-left: none;
		transform: rotate(45deg);
	}
	/*订单房源信息*/
	
	.HouseApply .HouseApply-houseinfo {
		margin-top: .42rem;
	}
	
	.HouseApply .hh-item {
		background: #fff;
		display: flex;
		justify-content: space-between;
		padding: .45rem .24rem;
		border-bottom: 1px solid #EEECEC;
		box-sizing: border-box;
	}
	
	.HouseApply .hhi-left {
		width: 1.3rem;
		display: flex;
		justify-content: space-between;
	}
	
	.HouseApply .hhi-right {
		display: flex;
		align-items: center;
	}
	
	.HouseApply .hhir-btn {
		display: block;
		width: .35rem;
		height: .35rem;
		text-align: center;
		border: 1px solid #e34648;
		box-sizing: border-box;
		color: #e34648;
		font-size: .35rem;
		line-height: .35rem;
		border-radius: .06rem;
	}
	
	.HouseApply .hhir-s {
		margin: 0 .3rem;
	}
	
	.HouseApply .hhir-g {
		color: #a4a4a4;
	}
	
	.HouseApply .hhi-leftb {
		font-size: .29rem;
		line-height: .42rem;
	}
	/*底部*/
	
	.HouseApply .HouseApply-flexbtn {
		width: 100%;
		display: flex;
		justify-content: space-between;
		margin-top: .42rem;
		background: #fff;
	}
	
	.HouseApply .hflr-img {
		width: .42rem;
		height: .56rem;
	}
	
	.HouseApply .hf-right {
		width: 2.84rem;
		height: 1.01rem;
		line-height: 1.01rem;
		text-align: center;
		color: #fff;
		background: #e34648;
	}
	
	.HouseApply .hf-left {
		width: 4.65rem;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 .4rem 0 .24rem;
		text-align: center;
		line-height: .31rem;
	}
	
	.HouseApply .hfl-left>p {
		font-size: .35rem;
		color: #E34648;
	}
	
	.HouseApply .hfl-left>span {
		display: block;
		font-size: .25rem;
		color: #a4a4a4;
		margin-top: .1rem;
	}
	
	.HouseApply #startDate,
	.HouseApply #endDate {
		width: initial;
	}
	
	.HouseApply #firstSelect {
		font-size: .31rem !important;
	}
	
	.HouseApply .labeldate {
		/*width: 1.5rem !important;*/
		font-size: .28rem;
	}
</style>